#include "ctproxyrunnable.h"

CTProxyRunnable::CTProxyRunnable(QVector<ProxyServerData> proxyVects)
{
    m_proxyVects = proxyVects;
}
CTProxyRunnable::~CTProxyRunnable()
{
    qDebug()<<"~CTProxyRunnable()";
}
void CTProxyRunnable::run()
{
    // SOCKS5 代理设置
    QNetworkProxy proxy;
    proxy.setType(QNetworkProxy::Socks5Proxy);

    int rowidx=0;
    foreach (const auto aps, m_proxyVects) {

        proxy.setHostName("122.9.54.111"); // 替换成你的 SOCKS5 代理服务器地址
        proxy.setPort(1080);       // 替换成你的 SOCKS5 代理服务器端口
        // 如果需要身份验证
        // proxy.setUser("your_username");           // 替换成你的用户名（如果有的话）
        // proxy.setPassword("your_password");       // 替换成你的密码（如果有的话）
        // 设置全局网络代理
        //QNetworkProxy::setApplicationProxy(proxy);
        m_manager.setProxy(proxy);
        QString urlstr = "https://www.google.com";
        m_request.setUrl(QUrl(urlstr));
        m_reply = m_manager.get(m_request);
        qDebug()<<proxy;

        connect(m_reply, &QNetworkReply::finished, [this]() {
            this->onFinished(m_reply);
        });

    }




//    foreach(const auto & dn, m_dnVects) {
//        auto clientSocket = new CTClientSocket();
//        clientSocket->setServerAddress(dn.address);
//        clientSocket->setServerPort(dn.port.toInt());
//        clientSocket->setSendMsg(dn.msg);
//        clientSocket->setRequestParam(dn.reqParam);
//        clientSocket->moveToThread(QThreadPool::globalInstance()->thread());
//        QMetaObject::invokeMethod(clientSocket, "startConnection");
//        //QThreadPool::globalInstance()->start(clientSocket);
//        QEventLoop loop;
//        connect(clientSocket, &CTClientSocket::dataSocketReceived, &loop, &QEventLoop::quit);
//        connect(clientSocket, &CTClientSocket::dataSocketReceived, this,
//                [&](QByteArray data, QString requestParam){
//                    dataReceivedFromSocket(data, requestParam);

//                });
//        loop.exec();


}
void CTProxyRunnable::onFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        QString response(data);
        if (!response.isEmpty()) {
            qDebug() << "代理服务器可用。来自example.com的响应:\n" << response;
        } else {
            qDebug() << "从example.com收到空响应";
        }
    } else {
        qDebug() << "代理服务器不可用或发生错误：" << reply->errorString();
    }
    reply->deleteLater();
}
